package Util;
// Introduced in Chapter 17
import java.io.*;

/** BTree storing many ints on disk. */
public class BTree<T extends Comparable<T>>{


	//Root Node of Tree
	private BTreeNode<T> rootNode;
  
  /** A new BTree is initially empty. */
  public BTree() {
    rootNode = new BTreeNode<T>(true);    
  }

  /** Add target to this BTree and write any modified nodes to disk. */
  public void add(T target) {    
    if (rootNode.isFull()) {
      BTreeNode<T> parent = new BTreeNode<T>(rootNode);
      rootNode = parent;      
      parent.add(target);
    } else {
      rootNode.add(target);
    }
  }

  /** Return true if this BTree contains target. */
  public boolean contains(T target) {
    BTreeNode<T> node = rootNode;
    while (node != null) {
      double d = node.indexOf(target);
      int i = (int)d;
      if (i == d) {
        return true;
      } else {
        node = node.getChild(i);
      }
    }
    return false;
  }

  /* Dont need
  //Read a previously saved BTree from disk.
  public static BTree readFromDisk() {
    try {
      ObjectInputStream in
        = new ObjectInputStream
        (new FileInputStream(DIR + "btree"));
      return (BTree)(in.readObject());
    } catch (Exception e) {
      e.printStackTrace();
      System.exit(1);
      return null;
    }
  }
*/
  /** Remove target from this BTree. */
  public void remove(T target) {
    rootNode.remove(target);
    if ((rootNode.size() == 1) && (!(rootNode.isLeaf()))) {
      rootNode = rootNode.getChild(0);      
    }
  }
}
